from socket import *
from time import sleep

class sockwrap:
	def __init__(self,host="localhost",port=6000):
		"""This function creates a socket and connects to the server.
		Input: teamname, robocup server address and port
		Output: void
		"""	
		self.sock = socket(AF_INET, SOCK_DGRAM)
		self.sock.setblocking(0)
		self.serv_host = host
		self.serv_port = port
		# self.sock.connect((host,port))
        
	def close(self):
		"This functions closes the connection. That's it."
		self.sock.close()
		
	def send(self,data):
		"""This function sends data to the server.
		Input: a string of characters to send to the server
		Output: how many bytes were sent. -1 if error
		"""
		# return self.sock.send(data+'\x00')
		return self.sock.sendto(data+'\x00', (self.serv_host, self.serv_port))
		
	def grab(self, errCount = 0):
		"""This function grabs data from the server
		Input: nothing
		Output: a string holding the data received, or None if server doesn't respond after 2s
		"""
		try: return self.sock.recvfrom(8192);
		except error, e: # socket.error
			sleep(0.02)
			print "Error: "+str(e)
			if errCount > 100: return None
			else: return self.grab(errCount+1)
